package io.litchi.auth.Infrastructure.util;

import com.nimbusds.jose.shaded.gson.Gson;
import com.nimbusds.jose.shaded.gson.GsonBuilder;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * description: http响应util
 *
 * @author helang
 * @since 2025-09-10
 */
public class ResponseUtil {


    // ✅ 复用 Gson 实例
    private static final Gson gson = new GsonBuilder().create();

    private static final String JSON_MEDIA_TYPE = "application/json;charset=utf-8";
    /**
     * 向响应中写入 JSON 数据
     *
     * @param response HttpServletResponse
     * @param status   HTTP 状态码（如 200, 401, 403）
     * @param data     要序列化的对象
     * @param <R>      泛型类型
     * @throws IOException 写出异常
     */
    public static <R> void writeJsonResponse(HttpServletResponse response, int status, R data) throws IOException {
        response.setStatus(status);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(JSON_MEDIA_TYPE);

        PrintWriter writer = response.getWriter();
        writer.write(gson.toJson(data));
        writer.flush();
    }

    // 默认 200
    public static <R> void writeJsonResponse(HttpServletResponse response, R data) throws IOException {
        writeJsonResponse(response, HttpStatus.OK.value(), data);
    }
}